package org.blogspot.t0yv0.marcalog.model

import javax.jdo._
import org.blogspot.t0yv0.marcalog.util._

sealed class DataManager(persistence: PersistenceManager) {
  private val pm = persistence;

  def byId[T](cl: Class[T], id: Any) =
    pm.getObjectById(cl, id)

  def find[T](cl: Class[T], field: String, key: Any) = {
    val q = pm.newQuery(cl);
    q.setFilter(field + " == x");
    q.declareParameters(key.asInstanceOf[AnyRef].getClass.getName + " x");
    Util.seq[T](q.execute(key))
  }

  def delete(entities: Seq[Entity]) {
    if (!entities.isEmpty) {
      pm.deletePersistentAll(Util.toCollection(entities));
    }
  }

  def all[T](cl: Class[T], offset: Int = 0, limit: Int = 0) = {
    val q = pm.newQuery(cl);
    if ((limit > 0) || (offset > 0)) {
      q.setRange(offset, limit);
    }
    Util.seq[T](q.execute);
  }

  def insert(entities: Seq[Entity]) {
    if (!entities.isEmpty) {
      pm.makePersistentAll(Util.toCollection(entities));
    }
  }

  def close {
    pm.close;
  }
  
}
